package com.wiz.weixin.manager;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.wiz.weixin.common.TencentConstant;
import com.wiz.weixin.util.TencentUtil;

/***
 * 微信token，ticket管理器
 */
@Component("wxAccessManager")
public class WxAccessManager implements TencentConstant{
	/**
	 * --------------------------------必要常量管理--------------------start-------------------------
	 */
	private static String tencent_wx_token;
	private static String tencent_wx_ticket;

	public static String getTencent_wx_token() {
		return tencent_wx_token;
	}

	public synchronized static void setTencent_wx_token(String tencent_wx_token) {
		WxAccessManager.tencent_wx_token = tencent_wx_token;
	}

	public static String getTencent_wx_ticket() {
		return tencent_wx_ticket;
	}

	public synchronized static void setTencent_wx_ticket(String tencent_wx_ticket) {
		WxAccessManager.tencent_wx_ticket = tencent_wx_ticket;
	}
	/**
	 * --------------------------------必要常量管理--------------------end-------------------------
	 */
	
	private transient final Logger log = LoggerFactory.getLogger(getClass());
	
	private final String reset_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
			+ WX_APP_ID + "&secret=" + WX_APP_SECRET;
	
	private volatile int switchInt = 0;//重置开关
	
	/**
	 * 重置token
	 * @return
	 * @throws JSONException
	 */
	public synchronized boolean resetWxToken() throws JSONException {
		String response = TencentUtil.httpsRequest(reset_token_url,"GET",null);
		JSONObject json = new JSONObject(response);
		String token = json.getString("access_token");
		if (StringUtils.isNotBlank(token)) {
			WxAccessManager.setTencent_wx_token(token);
			int expiresTime = json.getInt("expires_in");
			if(expiresTime<3600){
				log.warn("get access_token from tencent,that expiresTime too short ="+expiresTime);
				resetTokenNextTime(expiresTime);
			}
			return true;
		}
		return false;
	}
	
	/**
	 * 获取微信JSSDK的ticket 
	 * @throws JSONException 
	 */
	public synchronized boolean resetJsApiTicket() throws JSONException {
		String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
		String requestUrl = url.replace("ACCESS_TOKEN", WxAccessManager.getTencent_wx_token());
		// 发起GET请求获取凭证
		String response = TencentUtil.httpsRequest(requestUrl,"GET",null);
		org.json.JSONObject jsonObject = new org.json.JSONObject(response);
		if (null != jsonObject) {
			try {
				WxAccessManager.setTencent_wx_ticket(jsonObject.getString("ticket"));
				return true; 
			} catch (JSONException e) {
				// 获取token失败
				log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
			}
		}
		return false;
	}

	/**
	 * 若token有效时间过短，执行意外操作
	 * @param expiresTime
	 */
	private void resetTokenNextTime(final int expiresTime){
		final int waitTime = 3500 - expiresTime;
		new Thread(){
			public void run(){
				try {
					log.warn("another reset token task have been started");
					sleep(waitTime);
					String response = TencentUtil.httpsRequest(reset_token_url,"GET",null);
					JSONObject json = new JSONObject(response);
					String token = json.getString("access_token");
					if (StringUtils.isNotBlank(token)) {
						WxAccessManager.setTencent_wx_token(token);
						resetJsApiTicket();
					}
				} catch (Exception e) {
				}
			}
		}.start();
	}
	
	/**
	 * 临时重启任务
	 */
	public void resetTempTask(){
		if(switchInt == 1){
			return;
		}
		switchInt = 1;
		new Thread(){
			public void run(){
				try {
					log.warn("3rd mode reset token task have been started,origin toekn="+getTencent_wx_token());
					sleep(30000);//30秒后重启
					String response = TencentUtil.httpsRequest(reset_token_url,"GET",null);
					JSONObject json = new JSONObject(response);
					String token = json.getString("access_token");
					if (StringUtils.isNotBlank(token)) {
						WxAccessManager.setTencent_wx_token(token);
						resetJsApiTicket();
						switchInt=0;
					}
				} catch (Exception e) {
					
				}
			}
		}.start();
	}
}
